package bm.com.ai.server.service.impl;

import bm.com.ai.server.LLModel.config.GlobalAiConfig;
import bm.com.ai.server.dto.MessageRequest;
import bm.com.ai.server.dto.MessageResponse;
import bm.com.ai.server.LLModel.constant.ModelType;
import bm.com.ai.server.service.AIService;
import bm.com.ai.server.LLModel.factory.ModelFactory;
import bm.com.ai.server.LLModel.strategy.ModelStrategy;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Service
@RequiredArgsConstructor
public class AIServiceImpl implements AIService {

    private final ModelFactory modelFactory;
    private final MeterRegistry meterRegistry;
    private ModelType defaultModelType = ModelType.QWEN;//默认模型

    @Resource
    GlobalAiConfig globalAiConfig;//默认模型

    // 用于会话特定的模型设置
    private final ConcurrentMap<String, ModelType> sessionModelPreferences = new ConcurrentHashMap<>();

    @Override
    public MessageResponse processMessage(MessageRequest request) {
        if (request.getModelType() != null) {
            request.setModelType(request.getModelType());
        } else {
            // 使用全局配置中的默认模型
            request.setModelType(ModelType.valueOf(globalAiConfig.getDefaultModel()));
        }

        Timer.Sample sample = Timer.start(meterRegistry);
        // 获取适当的策略
        ModelStrategy strategy = modelFactory.getStrategy(request);

        try{
            return strategy.process(request);
        } catch (Exception e) {
            sample.stop(meterRegistry.timer("ai.model.processing.time", "model", request.getModelType().name()));
        }

        return null;
    }


    /**
     * 健康检测
     * @return
     */
    @Override
    public String healthCheck() {
        StringBuilder healthReport = new StringBuilder("AI Service Health Check:\n");
//        modelFactory.initialize().forEach(strategy -> {
//            try {
//                // 简单的健康检查：尝试获取模型并生成一个简单响应
//                strategy.getModel().chat("health check");
//                healthReport.append("- Model strategy is healthy\n");
//            } catch (Exception e) {
//                healthReport.append("- Model strategy is unhealthy: ").append(e.getMessage()).append("\n");
//            }
//        });
        return healthReport.toString();
    }

    /**
     * 切换默认模型
     *
     * @param modelType
     * @return
     */
    @Override
    public ModelType switchDefaultModel(String modelType) {
        try {
            defaultModelType = ModelType.valueOf(modelType.toUpperCase());
            return defaultModelType;
        } catch (IllegalArgumentException e) {
            return ModelType.valueOf(globalAiConfig.getDefaultModel());
        }
    }

    /**
     * 为特定会话设置模型偏好
     * @param sessionId
     * @param modelType
     * @return
     */
    public String setSessionModelPreference(String sessionId, String modelType) {
        try {
            ModelType type = ModelType.valueOf(modelType.toUpperCase());
            sessionModelPreferences.put(sessionId, type);
            return "Session " + sessionId + " set to use model: " + type;
        } catch (IllegalArgumentException e) {
            return "Invalid model type. Available models: " + String.join(", ", ModelType.values().toString());
        }
    }
}
